package com.ps.service.dept.imp;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.util.ArrayUtils;
import com.ps.dao.BaseDaoSupport;
import com.ps.dao.dept.WorkPositionDAO;
import com.ps.dao.person.EmployeeDAO;
import com.ps.entity.Result;
import com.ps.entity.Status;
import com.ps.entity.person.Manager;
import com.ps.global.ResultCode;
import com.ps.pojo.dept.Department;
import com.ps.pojo.dept.WorkPosition;
import com.ps.pojo.person.Employee;
import com.ps.service.BaseServiceSupport;
import com.ps.service.dept.WorkPositionService;
import com.ps.util.Kit;
import com.ps.util.PaginationSupport;
import com.ps.util.R;

public class WorkPositionServiceImp extends BaseServiceSupport<WorkPosition>
		implements WorkPositionService {
	@Autowired
	private WorkPositionDAO workPositionDAO;

	@Autowired
	private EmployeeDAO employeeDAO;
	
	@Override
	public BaseDaoSupport<WorkPosition> getBaseDao() {
		// TODO Auto-generated method stub
		return workPositionDAO;  
	}

	public boolean existsEmployee(Integer departmentId) {

		return false;
	}

	public Result findByPage(int pageSize, int startIndex) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(WorkPosition.class);
		ArrayList<Order> orders = new ArrayList<Order>();
		orders.add(Order.desc("wpId"));
		//orders.add(Order.desc("department.departmentId"));

		
		Result result = this.findPageByCriteria(detachedCriteria, pageSize, startIndex, orders);
		
		try {
			if (StringUtils.equals(result.getStatus().getCode(), Status.SUCCES)) {
				PaginationSupport<WorkPosition> paginationSupport = (PaginationSupport<WorkPosition> )result.getDatas();
				List<WorkPosition> list = paginationSupport.getItems();
				List<com.ps.entity.dept.WorkPosition> mlist = new ArrayList<com.ps.entity.dept.WorkPosition>();
				for (WorkPosition wp : list) {
					com.ps.entity.dept.WorkPosition eWp = new com.ps.entity.dept.WorkPosition();
					BeanUtils.copyProperties(wp, eWp, new String []{"department"});
					eWp.setDepartment(new com.ps.entity.dept.Department()); 
					if (wp.getDepartment() != null) { 
						BeanUtils.copyProperties(wp.getDepartment(), eWp.getDepartment(), new String []{"childDepartments"});
					}	
					mlist.add(eWp);
				}
				
            	PaginationSupport<com.ps.entity.dept.WorkPosition> pagination = 
            		new PaginationSupport(mlist, paginationSupport.getTotalCount(), paginationSupport.getPageSize(), paginationSupport.getStartIndex());
            	result.setDatas(pagination);
			}
		} catch (Exception e) {
			log.error("findByPage exception ", e);
		}
		
		return result;
	}

    public Result findByPageFromDept(int pageSize, int startIndex, Integer departmentId, Integer findByPageType) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(WorkPosition.class);
		switch (findByPageType) {
		case 1 :
			detachedCriteria.add(Restrictions.or(Restrictions.eq("department.departmentId", departmentId), Restrictions.isNull("department.departmentId")));
			break;
		case 2 :
			detachedCriteria.add(Restrictions.isNull("department.departmentId"));			
			break;
		case 3 :
			detachedCriteria.add(Restrictions.eq("department.departmentId", departmentId));
			break;	
		}
 
		
		
		ArrayList<Order> orders = new ArrayList<Order>();
		orders.add(Order.desc("department.departmentId"));
		orders.add(Order.asc("wpId"));
		
		Result result = this.findPageByCriteria(detachedCriteria, pageSize, startIndex, orders);
		
		try {
			if (StringUtils.equals(result.getStatus().getCode(), Status.SUCCES)) {
				PaginationSupport<WorkPosition> paginationSupport = (PaginationSupport<WorkPosition> )result.getDatas();
				List<WorkPosition> list = paginationSupport.getItems();
				List<com.ps.entity.dept.WorkPosition> mlist = new ArrayList<com.ps.entity.dept.WorkPosition>();
				for (WorkPosition wp : list) {
					com.ps.entity.dept.WorkPosition eWp = new com.ps.entity.dept.WorkPosition();
					BeanUtils.copyProperties(wp, eWp, new String []{"department"});
					mlist.add(eWp);
				}
				
            	PaginationSupport<com.ps.entity.dept.WorkPosition> pagination = 
            		new PaginationSupport(mlist, paginationSupport.getTotalCount(), paginationSupport.getPageSize(), paginationSupport.getStartIndex());
            	result.setDatas(pagination);
			}
		} catch (Exception e) {
			log.error("findByPage exception ", e);
		}
		
		return result;
	}

    
    
    
    

	public Result delete(Integer wpId, Integer deptId) {
		int count = employeeDAO.getCountByProperty("workPosition.wpId", wpId);
        if (count > 0) {
        	Result result = Kit.createResult();
			result.getStatus().setCode(Status.FAIL);
			result.getStatus().setMessage(R.string.getProperty("exist_work_pos_person_1"));
			result.setDatas(deptId);
			return result;
        } else {
        	return super.delete(wpId);
        }
		     
		
	}

	
	
	
	
	@Override
	public Result update(WorkPosition object) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(WorkPosition.class);
		detachedCriteria.setProjection(Projections.count("name"));
		detachedCriteria.add(Restrictions.eq("name", object.getName()));
		detachedCriteria.add(Restrictions.ne("wpId", object.getWpId()));
		Integer count = (Integer) workPositionDAO.getHibernateTemplate().findByCriteria(detachedCriteria).get(0);
		System.out.println(Kit.toJson(object));
		if (count > 0) {
			Result result = Kit.createResult();
			result.getStatus().setCode(Status.FAIL);
			result.getStatus().setMessage(R.string.getProperty("nameCantRepeat"));
			result.setDatas(workPositionDAO.findById(object.getWpId())) ;
			return result;
		}
		
	
		
		
		Result result = super.update(object);
		
		if (Status.SUCCES.equals(result.getStatus().getCode())) {
			/*
			 * 此处记录记录日志
			 */
		} else {
			result.setDatas(object);
		}
		
		return result;
	}

	
	
	
	@Override
	public Result save(WorkPosition object) {
		if (workPositionDAO.getCountByProperty("name", object.getName()) > 0) {
			Result result = Kit.createResult();
			result.getStatus().setCode(Status.FAIL);
			result.getStatus().setMessage(R.string.getProperty("nameCantRepeat"));
			result.setDatas(object);
			return result;
		}
		return super.save(object);
	}

	public Result delWPAndCountPersonIsZero(Integer departmentId,
			Integer inputerId) {
		Result result = Kit.createResult();
		Session session = workPositionDAO.getHibernateTemplate().getSessionFactory().openSession();
		Transaction tx  = null;

		try {
			
			List<WorkPosition> wpList =  this.workPositionDAO.findByProperty("department.departmentId", departmentId);
			
			if  (wpList == null || wpList.size() == 0) {
				result.getStatus().setCode(Status.FAIL);
				result.getStatus().setMessage(R.string.getProperty("queryempty"));
				return result;
			}
			
			tx = session.beginTransaction();
			String hql = "SELECT COUNT(employeeId) FROM Employee WHERE workPosition.wpId = ?";
			
			
			Iterator<WorkPosition> iter = wpList.iterator();
			while(iter.hasNext()) {
				WorkPosition wp = iter.next();
				
				Query query = session.createQuery(hql);
				query.setInteger(0, wp.getWpId());
				Long count = (Long) query.list().get(0);
				
				System.out.println("count = " + count);
	            if (count == 0) {
	            	wp.setDepartment(null);
	            	session.update(wp);
	            	//此处需要插入日志
	            	iter.remove();
	            	
	            } 
			}
			
			if (wpList.size() > 0) {
				result.getStatus().setCode(ResultCode.EXISTS_WORK_POSITION_PERSON);
				result.getStatus().setMessage(R.string.getProperty("exist_work_pos_person"));
				result.setDatas(departmentId);
				
			} else { 
				Query query = session.createQuery("DELETE FROM Department WHERE departmentId = ?");
				//此处需要插入日志
				query.setInteger(0, departmentId);
				query.executeUpdate();
				result.getStatus().setCode(ResultCode.DEL_SUCCES);
				result.getStatus().setMessage(R.string.getProperty("delsucces"));
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null) tx.rollback();
			if (session != null) session.close();
			log.error("delWPAndCountPersonIsZero exception ", e);
			result.getStatus().setCode(Status.FAIL);
			result.getStatus().setMessage(R.string.getProperty("delfail"));
		}
		
		
		
		return result;
	}

	public Result moveToDept(Integer departmentId, Integer orginDepartmentId,
			Integer inputerId) {
		Result result = Kit.createResult();
		Session session = workPositionDAO.getHibernateTemplate().getSessionFactory().openSession();
		Transaction tx  = null;
        try {
        	tx = session.beginTransaction();
        	String hql = "UPDATE WorkPosition SET department.departmentId = ? WHERE department.departmentId = ?";
        	Query query = session.createQuery(hql);
        	query.setInteger(0, departmentId);
        	query.setInteger(1, orginDepartmentId);
        	query.executeUpdate();
        	
			query = session.createQuery("DELETE FROM Department WHERE departmentId = ?");
			//此处需要插入日志
			query.setInteger(0, orginDepartmentId);
			query.executeUpdate();
			tx.commit();
			result.setDatas(departmentId);
			result.getStatus().setCode(ResultCode.UPDATE_SUCCES);
			result.getStatus().setMessage(R.string.getProperty("delsucces"));
        	
		} catch (Exception e) {
			if (tx != null) tx.rollback();
			if (session != null) session.close();
			log.error("moveToDept exception ", e);
			result.getStatus().setCode(Status.FAIL);
			result.getStatus().setMessage(R.string.getProperty("move_to_dept_fail"));
		}
         
		
		return result;
	}

	public Result moveToDeptForUpt(Integer departmentId, Integer orginDepartmentId,
			Integer[] wpIds, Integer inputerId) {
		Result result = Kit.createResult();
	
		Session session = workPositionDAO.getHibernateTemplate().getSessionFactory().openSession();
		Transaction tx  = null;
        try {
        	tx = session.beginTransaction();
        	String hql = "UPDATE WorkPosition SET department.departmentId = ? WHERE department.departmentId = ? AND wpId = ?";
        	Query query = session.createQuery(hql);
        	query.setInteger(0, departmentId);
        	query.setInteger(1, orginDepartmentId);
        	
        	if (ArrayUtils.isNotEmpty(wpIds)) {
            	for (Integer wpId : wpIds) {
            		query.setInteger(2, wpId);
            		query.executeUpdate();
            	}
        	} 
        	tx.commit();
			//此处需要插入日志
			result.setDatas(orginDepartmentId);
			result.getStatus().setCode(ResultCode.UPDATE_SUCCES);
			result.getStatus().setMessage(R.string.getProperty("move_to_dept_succes"));
        	
		} catch (Exception e) {
			if (tx != null) tx.rollback();
			if (session != null) session.close();
			log.error("moveToDeptForUpt exception ", e);
			result.getStatus().setCode(Status.FAIL);
			result.getStatus().setMessage(R.string.getProperty("move_to_dept_fail"));
		}
         
		
		return result;
	}

    
}
